package org.wang.generalcode.modules.sys.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.wang.generalcode.modules.sys.pojo.entity.Dept;
import org.wang.generalcode.modules.sys.pojo.model.Option;
import org.wang.generalcode.modules.sys.pojo.params.DeptQueryParams;
import org.wang.generalcode.modules.sys.service.IDeptService;
import org.wang.generalcode.modules.sys.pojo.vo.DeptVO;
import org.wang.generalcode.support.mybaties.Condition;
import org.wang.generalcode.support.result.Result;

import javax.validation.Valid;
import java.util.List;

/**
 * 部门表 控制器
 *
 * @author wz
 * @since 2024-08-08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/dept")
@Schema(description = "部门表", name = "部门表接口")
public class DeptController {

	private final IDeptService deptService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Schema(description = "详情", example = "传入dept")
	public Result<Dept> detail(Dept dept) {
		Dept detail = deptService.getOne(Condition.getQueryWrapper(dept));
		return Result.success(detail);
	}

	/**
	 * 分页 部门表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Schema(description = "分页", example = "传入dept")
	public Result<List<DeptVO>> list(DeptQueryParams queryParams) {
		return Result.success(deptService.getDeptList(queryParams));
	}

	/**
	 * 部门下拉列表
	 * @return
	 */
	@GetMapping("/options")
	@Schema(description = "部门下拉列表", example = "部门下拉列表")
	public Result<List<Option<Long>>> getDeptOptions() {
		List<Option<Long>> list = deptService.listDeptOptions();
		return Result.success(list);
	}


	/**
	 * 新增 部门表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Schema(description = "新增", example = "传入dept")
	public Result save(@Valid @RequestBody Dept dept) {
		return Result.judge(deptService.save(dept));
	}

	/**
	 * 修改 部门表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Schema(description = "修改", example = "传入dept")
	public Result update(@Valid @RequestBody Dept dept) {
		return Result.judge(deptService.updateById(dept));
	}


	/**
	 * 删除 部门表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@Schema(description = "删除", example = "传入ids")
	public Result remove(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		if (StrUtil.isNotBlank(ids)) {
			String[] menuIds = ids.split(",");
			for (String deptId : menuIds) {
				deptService.remove(Wrappers.<Dept>lambdaQuery()
						.eq(Dept::getId, deptId)
						.or()
						.apply("CONCAT (',',tree_path,',') LIKE CONCAT('%,',{0},',%')", deptId));
			}
		}
		return Result.judge(true);
	}


}
